package com.qf.web.controller;

import com.qf.domain.Cart;
import com.qf.domain.Goods;
import com.qf.domain.User;
import com.qf.service.CartService;
import com.qf.service.GoodsService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;


@WebServlet("/cartservlet")
public class CartServlet extends BaseServlet {

    /*添加购物车*/
    //http://localhost:8080/cartservlet?method=addCart&goodsId=1&number=1
    public String addCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //判断用户是否登录
        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //获取参数
        String goodsId = request.getParameter("goodsId");
        String number = request.getParameter("number");
        //校验
        if(StringUtils.isEmpty(goodsId)){
            request.setAttribute("msg","商品id不能为空");
            return "/message.jsp";
        }
        int num = 1;//默认对商品不进行加减处理
        if(!StringUtils.isEmpty(number)){
            try {
                num = Integer.parseInt(number);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        try {
            //调用业务逻辑
            CartService cartService = new CartServiceImpl();
            int good_id= Integer.parseInt(goodsId);//前端的商品id String类型所以需要转化
            //查询商品信息  封装购物车对象需要四个属性，money需要单价×数量，而单价需要商品表，所以需要商品服务层的逻辑处理
            GoodsService goodsService = new GoodsServiceImpl();
            Goods goods = goodsService.findById(good_id);
            //查看购物车是否存在这个商品（同一用户，添加同一商品，id，pid一样了主键不对了，所以需要解决一下  购物车有这个商品做数量更新）
            Cart cart = cartService.find(user.getId(),good_id);
            if (cart != null) {//更新数量
                cart.setNum(cart.getNum()+num);//数量更新，总价也应更新
                cart.setMoney(goods.getPrice().multiply(new BigDecimal(cart.getNum())));
                cartService.modify(cart);
            }else{//新增购物车操作
                cart = new Cart(user.getId(),good_id,num,goods.getPrice().multiply(new BigDecimal(num)));//需要加一个所以就封装一个先
                cartService.add(cart);
            }
            return "redirect:/cartSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","添加购物车失败"+e.getMessage());
            return "/message.jsp";
        }

    }
    /*
    * 查看购物车功能    根据用户id查的
    * */
   // http://localhost:8080/cartservlet?method=getCart
   public String getCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //判断用户是否登录  登录了才能得到用户id
       User user = (User)request.getSession().getAttribute("user");
       if (user == null) {
           return "redirect:/login.jsp";
       }
       try {
           //调用业务逻辑  前端又没数据
           CartService cartService= new CartServiceImpl();
           List<Cart> cartList = cartService.find(user.getId());//一个用户很多条购物记录所以返回的是一个集合
           //转发重定向
           request.setAttribute("cartList", cartList);
           return "/cart.jsp";
       } catch (Exception e) {
           e.printStackTrace();
           request.setAttribute("msg", "查看购物车失败：" + e.getMessage());
           return "/message.jsp";
       }


   }
   /*ajax 操作购物车*/
   // cartservlet?method=addCartAjax&goodsId="+pid+"&number=1
   public String addCartAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //判断用户是否登录  登录了才能得到用户id
       User user = (User)request.getSession().getAttribute("user");
       if (user == null) {
           return "redirect:/login.jsp";
       }
       //获取参数
       String goodsId = request.getParameter("goodsId");
       String number = request.getParameter("number");//1 -1 0
       //非空验证
       if(StringUtils.isEmpty(goodsId)){
           request.setAttribute("msg","商品id不能为空");
           return "/message.jsp";
       }
       try {
           //4调用业务逻辑
           int good_id = Integer.parseInt(goodsId);
           int num = Integer.parseInt(number);
           CartService cartService = new CartServiceImpl();
           if(num==0){//删除商品
               cartService.remove(user.getId(),good_id);//购物车里边全国人民买的东西的数据都有，所以是根据用户id，商品id删除
           }else if(num==1||num==-1){//更新功能
               //查找商品
               Cart cart = cartService.find(user.getId(), good_id);
               if (cart != null) {
                   GoodsService goodsService = new GoodsServiceImpl();
                   Goods goods = goodsService.findById(good_id);
                   cart.setNum(cart.getNum()+num);
                   cart.setMoney(goods.getPrice().multiply(new BigDecimal(cart.getNum())));
                   cartService.modify(cart);
                   //正确的话他走的是ajax处理就不用管了
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
           request.setAttribute("msg","更新购物车失败"+e.getMessage());
           return "/message.jsp";
       }
       return null;
   }

   /*清空购物车*/
   //cartservlet?method=clearCartAjax
   public String clearCartAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //判断用户是否登录  登录了才能得到用户id
       User user = (User)request.getSession().getAttribute("user");
       if (user == null) {
           return "redirect:/login.jsp";
       }
       try {
           //调用业务逻辑
           CartService cartService = new CartServiceImpl();
           cartService.clear(user.getId());//根据用户id所有的商品删除即可
       } catch (Exception e) {
           e.printStackTrace();
           request.setAttribute("msg","清空购物车失败"+e.getMessage());
           return "/message.jsp";
       }
       return null;//代表json ajax处理
   }
}


